package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"shop/models"
)

type ShopController struct {
	beego.Controller
}
type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopController) List() {
	var allshop []models.Shops
	err := models.DB.Find(&allshop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "展示成功",
			Data: allshop,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Add() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	zl, _ := c.GetFloat("zl")
	sl, _ := c.GetFloat("sl")
	time := c.GetString("time")
	allshop := models.Shops{
		Name:  name,
		Price: price,
		Zl:    zl,
		Sl:    sl,
		Time:  time,
	}
	if name == "" || price == 0 || zl == 0 || sl == 0 || time == "" {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "数据不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	err := models.DB.Create(&allshop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Shops{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Up() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	zl, _ := c.GetFloat("zl")
	sl, _ := c.GetFloat("sl")
	time := c.GetString("time")
	allshop := models.Shops{
		Id:    id,
		Name:  name,
		Price: price,
		Zl:    zl,
		Sl:    sl,
		Time:  time,
	}

	err := models.DB.Save(&allshop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
